package com.litchi.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.GetListener;

import com.activeandroid.query.Select;
import com.lib.uil.ToastUtils;
import com.litchi.R;
import com.litchi.adapter.GoodsGridAdapter;
import com.litchi.adapter.MyPagerAdapter;
import com.litchi.app.MyApplication;
import com.litchi.app.SysApplication;
import com.litchi.bean.Goods;
import com.litchi.bean.GoodsHistory;
import com.litchi.bean.InCart;
import com.litchi.utils.Constants;
import com.litchi.utils.DBUtils;
import com.litchi.utils.NumberUtils;

public class DetailActivity extends FragmentActivity implements OnClickListener {

	private ViewPager mPager;
	private ImageView mImgFavor;
	private TextView mTvCollect;
	private com.litchi.utils.menudrawer.MenuDrawer mDrawer;

	private Goods mGoods;
	private ArrayList<GoodsHistory> historyList = new ArrayList<GoodsHistory>();
	private GoodsGridAdapter mAdapter;
	private MyApplication mApplication;
	private TextView mTvCount;
	private int isFavor = 0;
	private TextView mTvInCartNum;

	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SysApplication.getInstance().addDetailActivity(this);
		SysApplication.getInstance().removeExtraActivity();
		mContext = this;
		initData();
		saveHistory();
		initMenu();
		initView();
		setOnListener();
		initPager();
		initListView();
		initInCartNum();
		initHistory();
	}

	private void setOnListener() {
		findViewById(R.id.btn_add_to_cart).setOnClickListener(this);
		findViewById(R.id.btn_goto_cart).setOnClickListener(this);
		findViewById(R.id.btn_collect).setOnClickListener(this);
		findViewById(R.id.img_history).setOnClickListener(this);
		findViewById(R.id.img_back).setOnClickListener(this);
	}

	private void initView() {
		mTvInCartNum = (TextView) findViewById(R.id.tv_incart);
		mTvCount = (TextView) findViewById(R.id.tv_count_page);
		mTvCollect = (TextView) findViewById(R.id.tv_collect);
		mImgFavor = (ImageView) findViewById(R.id.img_favor);
		TextView tvTitle = (TextView) findViewById(R.id.tv_title);
		TextView tvPrice = (TextView) findViewById(R.id.tv_price);
		TextView tvVip = (TextView) findViewById(R.id.tv_vip);
		ImageView imgVip = (ImageView) findViewById(R.id.img_vip);
		tvTitle.setText(mGoods.getGoodsName());
		tvPrice.setText(NumberUtils.formatPrice(mGoods.getGoodsPrice()));
		// 判断是否收藏
		if (DBUtils.hasFavor(mGoods.getObjectId())) {
			mTvCollect.setText("已关注");
			mImgFavor.setImageResource(R.drawable.pd_collect_p);
		}

		imgVip.setVisibility(View.VISIBLE);
		tvVip.setVisibility(View.VISIBLE);

	}

	private void initData() {
		mApplication = (MyApplication) this.getApplicationContext();
		Intent intent = getIntent();
		mGoods = (Goods) intent.getSerializableExtra(Constants.GOODS_KEY);

	}

	/**
	 * 保存到浏览历史
	 */
	private void saveHistory() {
		GoodsHistory info = new Select().from(GoodsHistory.class).where("goodsId=? AND isFavor=0", mGoods.getObjectId())
				.executeSingle();
		// 删除同样的数据
		if (info != null) {
			info.delete();
		}
		// 插入到历史数据库

		DBUtils.save(new GoodsHistory(mGoods.getObjectId(), mGoods.getGoodsName(), mGoods.getGoodsImg().getUrl(),
				Double.parseDouble(mGoods.getGoodsPrice()), 0));
	}

	/**
	 * 购物车中商品数量
	 */
	private void initInCartNum() {
		int num = DBUtils.getInCartNum();
		if (num > 0) {
			mTvInCartNum.setVisibility(View.VISIBLE);
			mTvInCartNum.setText("" + num);
		} else {
			mTvInCartNum.setVisibility(View.INVISIBLE);
		}
	}

	private void initPager() {
		mPager = (ViewPager) findViewById(R.id.pager);
		FragmentManager fm = getSupportFragmentManager();

		List<ImageView> images = new ArrayList<>();

		ImageView image1 = new ImageView(this);
		ImageView image2 = new ImageView(this);
		ImageView image3 = new ImageView(this);
		ImageView image4 = new ImageView(this);

		mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mGoods.getGoodsImg1().getUrl(), image1);
		mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mGoods.getGoodsImg2().getUrl(), image2);
		mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mGoods.getGoodsImg3().getUrl(), image3);
		mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mGoods.getGoodsImg4().getUrl(), image4);
		images.add(image1);
		images.add(image2);
		images.add(image3);
		images.add(image4);
		MyPagerAdapter adapter = new MyPagerAdapter(images);
		mPager.setAdapter(adapter);
		mPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				mTvCount.setText(arg0 + 1 + "");
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
	}

	/**
	 * 
	 * init listview about history
	 */
	private void initListView() {
		ListView listView = (ListView) findViewById(R.id.menu_listView);
		mAdapter = new GoodsGridAdapter(mContext,historyList);
		listView.setAdapter(mAdapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				mDrawer.toggleMenu();
				 
				String goodsId = historyList.get(position).getGoodsId();

				BmobQuery<Goods> query = new BmobQuery<Goods>();
				query.getObject(mContext, goodsId, new GetListener<Goods>() {

					@Override
					public void onSuccess(Goods arg0) {
						// TODO Auto-generated method stub

						Intent intent = new Intent(mContext, DetailActivity.class);
						intent.putExtra(Constants.GOODS_KEY, arg0);
						mContext.startActivity(intent);

					}

					@Override
					public void onFailure(int code, String arg0) {
						// TODO Auto-generated method stub
						ToastUtils.showToast(mContext, "请检查网络连接" + arg0);
					}

				});

			}
		});
	}

	private void initHistory() {
		new HistoryTask().execute();
	}

	private void initMenu() {
		mDrawer = com.litchi.utils.menudrawer.MenuDrawer.attach(this,
				com.litchi.utils.menudrawer.MenuDrawer.Type.OVERLAY, com.litchi.utils.menudrawer.Position.END);
		mDrawer.setMenuView(R.layout.menudrawer_history);
		mDrawer.setContentView(R.layout.activity_detail);
		// 菜单宽度
		mDrawer.setMenuSize(260);
		// 菜单无阴影
		mDrawer.setDropShadowEnabled(false);
	}

	

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_back:
			finish();
			break;
		case R.id.btn_goto_cart: // 购物车
			gotoHomePage();
			break;
		case R.id.btn_collect: // 收藏
			collect();
			break;
		case R.id.btn_add_to_cart: // 加入购物车
			add2Cart();
			break;
		case R.id.img_history: // 浏览记录
			mDrawer.toggleMenu();
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (mDrawer.isMenuVisible()) {
				mDrawer.closeMenu();
				return false;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 加入购物车
	 */
	private void add2Cart() {
		InCart inCart = new Select().from(InCart.class).where("goodsId=?", mGoods.getObjectId()).executeSingle();
		if (inCart != null) {
			// 若购物车中有，则数量+1
			inCart.setNum(inCart.getNum() + 1);
			inCart.save();
		} else {

			new InCart(mGoods.getObjectId(), mGoods.getGoodsName(), mGoods.getGoodsImg().getUrl(),
					Double.parseDouble(mGoods.getGoodsPrice()), isFavor, 1).save();
		}
		// 刷新购物车商品数量
		initInCartNum();
		// Toast.makeText(this, "已添加到购物车", Toast.LENGTH_SHORT).show();
		ToastUtils.showToast(this, "已添加至购物车");
		// 通知主页刷新购物车商品数
		Intent intent = new Intent();
		intent.setAction(Constants.BROADCAST_FILTER.FILTER_CODE);
		intent.putExtra(Constants.BROADCAST_FILTER.EXTRA_CODE, Constants.INTENT_KEY.REFRESH_INCART);
		sendBroadcast(intent);
	}

	/**
	 * 跳转到首页购物车
	 */
	private void gotoHomePage() {
		startActivity(new Intent(this, MainActivity.class));
		Intent intent = new Intent();
		intent.setAction(Constants.BROADCAST_FILTER.FILTER_CODE);
		intent.putExtra(Constants.BROADCAST_FILTER.EXTRA_CODE, Constants.INTENT_KEY.FROM_DETAIL);
		sendBroadcast(intent);
		finish();
		overridePendingTransition(0, 0);
	}

	/**
	 * 收藏/取消收藏
	 */
	private void collect() {
		// 判断是否收藏

		if (DBUtils.hasFavor(mGoods.getObjectId())) {
			// 由于DBUtil的方法，需要设置favor = 1，否则会无法取消关注

			DBUtils.chanelFav(mGoods.getObjectId());
			mTvCollect.setText("关注");
			mImgFavor.setImageResource(R.drawable.pd_collect_n);
			ToastUtils.showToast(this, "取消成功");
		} else {

			DBUtils.save(new GoodsHistory(mGoods.getObjectId(), mGoods.getGoodsName(), mGoods.getGoodsImg().getUrl(),
					Double.parseDouble(mGoods.getGoodsPrice()), 1));
			mTvCollect.setText("已关注");
			mImgFavor.setImageResource(R.drawable.pd_collect_p);
			ToastUtils.showToast(this, "关注成功");
		}
		// 通知收藏界面刷新
		Intent intent = new Intent();
		intent.setAction("updateFavor");
		sendBroadcast(intent);
	}

	
 

	class HistoryTask extends AsyncTask<Void, Void, List<GoodsHistory>> {

		@Override
		protected List<GoodsHistory> doInBackground(Void... params) {
			return DBUtils.getHistory();
		}

		@Override
		protected void onPostExecute(List<GoodsHistory> result) {
			super.onPostExecute(result);
			historyList.clear();
			historyList.addAll(result);
			mAdapter.notifyDataSetChanged();
			DetailActivity.this.findViewById(R.id.progressBar1).setVisibility(View.GONE);
		}

	}

	public String getImageUlrByPositon(Goods mGoods, int position) {
		String url = "";
		switch (position) {
		case 1:
			url = mGoods.getGoodsImg1().getUrl();
			break;
		case 2:
			url = mGoods.getGoodsImg2().getUrl();
			break;
		case 3:
			url = mGoods.getGoodsImg3().getUrl();
			break;
		case 4:
			url = mGoods.getGoodsImg4().getUrl();
			break;

		default:
			break;
		}
		return url;
	}

}
